const app = getApp()
const WXAPI = require('../../wxapi/main')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    timer: null,
    userInfo: {},
    partUserInfo: null,
    reqId: '',
    reqDetail: null,
    taskDetailId: '',
    taskDetail: null,
    isTaskNewFlag: true,
    wordList: [],
    content: '',
    // 当前登录者信息
    login: {
      id: 'ojNDi5CBNHBda4sH4xNAb7dLNY1E', // open id
      user: '大猪蹄子',
      avatar: 'https://img2.baidu.com/it/u=1581320883,910100018&fm=253&app=53&size=w500&n=0&g=0n&f=jpeg?sec=1686045994&t=9135844131fa04a7ad00686d88c76752'
    },
    // 聊天信息
    chatList: [],
    isJump: false,
    isMaster: false,
  },

  // 输入监听
  inputClick(e) {
    this.setData({
      content: e.detail.value
    })
  },
  // 发送监听
  sendClick() {
    var that = this;
    var list = that.data.chatList;
    // 获取当前时间
    var date = new Date();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minu = date.getMinutes();
    var now1 = month < 10 ? '0' + month : month;
    var now2 = day < 10 ? '0' + day : day;
    // 组装数据
    // var skey = '196b253b1d6f72d318d2bf008431297a9d9a34a1'
    var skey = wx.getStorageSync('loginFlag')
    var taskId = that.data.taskDetailId
    var wordTxt = that.data.content
    // var msg = {
    //     msgId: this.data.login.id,
    //     nickname: this.data.login.user,
    //     avatar: this.data.login.avatar,
    //     message: this.data.content,
    //     type: 'text',
    //     date: now1 + '-' + now2 + ' ' + hour + ':' + minu
    // }
    let _postData = { skey, taskId, wordTxt }
    console.log('post data ', _postData)
    // return
    WXAPI.saveTaskWord(_postData)
      .then(function (res) {
        console.log('save word ', res)
        if (res.code === 0) {
          var _word = res.data
          console.log('_word id ', _word)
          that.clearTimer()
          that.onShow()
          that.scrollToBottom();
          that.setData({
            content: ''
          })
          // that.setData({
          //   chatList: list.concat(_word)
          // }, () => {
          //     that.scrollToBottom();
          //     that.setData({
          //         content: ''
          //     })
          // })
        } else {
          // 
          wx.showToast({
            title: res.msg,
            icon: 'error'
          })
        }
      })

  },
  // 滑动到最底部
  scrollToBottom() {
    setTimeout(() => {
      wx.pageScrollTo({
        scrollTop: 200000,
        duration: 3
      });
    }, 600)
  },

  // 加载记录
  loadChatList: function (_taskId) {
    var that = this
    WXAPI.loadTaskWordByTaskId({ taskId: _taskId })
      .then(function (res) {
        if (res.code === 0) {
          var _wordList = res.data
          console.log('flush wordList size ', that.timer)
          that.setData({
            chatList: _wordList
          })
        } else {
          // not word list
        }
      })
  },

  /**
   * 生命周期函数--监听页面加载
   */

  loadTask: function (_taskId) {
    var that = this
    WXAPI.loadTaskByTaskId({ taskId: _taskId })
      .then(function (res) {
        console.log('find task ', res.data)
        if (res.code === 0) {
          var _taskDetail = res.data
          console.log('taskDetail ', _taskDetail)
          that.setData({
            taskDetailId: _taskDetail.taskId,
            taskDetail: _taskDetail,
            isTaskNewFlag: false
          })
          //      
        } else {
          // 数据是空的
          that.setData({
            isTaskNewFlag: true
          })
        }
      })
  },

  // 加载当前taskId
  loadTaskByCurrUser: function () {
    var that = this
    let currentOpenId = that.data.partUserInfo.openid
    let getData = { reqId: that.data.reqId, openId: currentOpenId }
    WXAPI.loadTaskByTaskOpenId(getData)
      .then(function (res) {
        console.log('find task by open id ', res.data)
        if (res.code === 0) {
          var _taskDetail = res.data
          console.log('taskDetail by open id ', _taskDetail)
          that.setData({
            taskDetailId: _taskDetail.taskId,
            taskDetail: _taskDetail,
            isTaskNewFlag: false
          }, () => {
            that.clearTimer()
            if (!that.data.isJump) {
              that.onShow()
            }
          })
          //     
        } else {
          // 任务数据是空的
          that.setData({
            isTaskNewFlag: true
          })
        }
      })
  },

  loadDatas: function (_reqId) {
    var that = this;
    WXAPI.loadReqOne({ reqId: _reqId })
      .then(function (res) {
        console.log('find req detail ', res)
        if (res.code === 0) {
          var _reqDetail = res.data
          let currentOpenId = that.data.partUserInfo?.openid
          console.log('currentOpenId & openId : ', currentOpenId, _reqDetail.openId)
          console.log('that.data.taskDetailId: ', that.data.taskDetailId)
          if (currentOpenId) {
            if (_reqDetail.openId === currentOpenId) {
              that.setData({
                isMaster: true
              })
            }
            if (_reqDetail.openId === currentOpenId && !that.data.taskDetailId) {
              console.log('要跳转倒我的明细界面')
              that.setData({
                isJump: true
              })
              wx.redirectTo({
                url: '/pages/req-detail/index?reqId=' + _reqId,
              })
              return
            } else {
              // 不是本人
            }
          }
          that.setData({
            reqDetail: _reqDetail,
          })
        } else {
          wx.showModal({
            title: '错误',
            content: '没有找到该商品',
            showCancel: false,
          })
          return
        }
      })
  },

  onLoad(e) {
    console.log('load', e)
    var that = this
    var _reqId = ''
    var _taskId = ''
    if (e.scene) {
      console.log('scene ', e.scene)
      _reqId = e.scene     
    } else {
      _reqId = e.reqId
      _taskId = e.taskId
      if (_reqId === undefined || _reqId === '') {
        wx.redirectTo({
          url: '/pages/error/index',
        })
        return
      }
      if (_taskId !== undefined && _taskId !== '') {
        that.setData({ taskDetailId: _taskId })
      }
    }
    that.setData({ reqId: _reqId })
    // 设置当前用户
    var _partUserInfo = wx.getStorageSync('partUserInfo')
    if (_partUserInfo) {
      that.setData({
        partUserInfo: _partUserInfo
      })
    }

  },

  goChat() {
    let that = this;
    var _partUserInfo = wx.getStorageSync('partUserInfo')
    if (!_partUserInfo) {
      app.goLoginPageTimeOut()
      return
    } else {
      that.setData({
        partUserInfo: _partUserInfo
      })
    }
    console.log(that.data.reqDetail.openId)
    console.log(_partUserInfo.openid)
    if (that.data.reqDetail.openId == _partUserInfo.openid) {
      wx.showToast({
        title: '自己不能领自己的任务哦',
        icon:'error'
      })
      return
    }
    
    wx.showModal({
      title: '确认操作',
      content: '确认接受该需求订单，进一步洽谈合作？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          var skey = wx.getStorageSync('loginFlag')
          var _reqId = that.data.reqId
          var _postData = { reqId: _reqId, skey: skey }
          console.log('post data ', _postData)
          WXAPI.receiveReq(_postData)
            .then(function (res) {
              console.log('receive task ', res)
              if (res.code === 0) {
                var _taskDetailId = res.data.taskId
                console.log('_taskDetail id ', _taskDetailId)
                that.setData({
                  taskDetailId: _taskDetailId,
                  isTaskNewFlag: false
                })
                wx.showToast({
                  title: '需求接受成功，祝你洽谈顺利！',
                })
              } else {
                that.setData({
                  isTaskNewFlag: true
                })
              }
            })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  goComplete() {
    let that = this
    let _reqStatus ='completed'
    let _content = that.data.reqDetail.isReward == 0 ? '洽谈完毕后将关闭与对方的会话，确认关闭？' : '洽谈完毕后将关闭与对方的会话，由于您发布的需求设有悬赏，请确保已兑付悬赏。'
    wx.showModal({
      title: '洽谈完毕',
      content: _content,
      success(res) {
        if (res.confirm) {
          let postData = { reqId: that.data.reqId, reqStatus: _reqStatus }
          console.log('post data ', postData)
          wx.showLoading({
            title: '处理中,请稍等',
          })
          WXAPI.completeReq(postData)
            .then(res => {
              console.log('res ', res)
              if (res.code === 0) {
                // wx.showToast({
                //   title: '需求完成',
                //   icon: 'success'
                // })
                wx.hideLoading()
                wx.switchTab({
                  url: '/pages/req-mgr/index',
                })
              } else {
                wx.showToast({
                  title: res.message,
                  icon: 'error'
                })
              }
            })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  //定义定时器
  // setTimer() {
  //   let self = this;
  //   self.timer = setInterval(() => {
  //     self.loadChatList();
  //   }, 1000);
  // },
  //清除定时器
  clearTimer() {
    clearInterval(this.timer);//如果发现这个clearInterval不生效，写法又没问题
    this.timer = null;//自己把timer置为null就好了
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this
    var _reqId = that.data.reqId
    var _taskId = that.data.taskDetailId
    console.log('on show reqid, taskid ', _reqId, _taskId)
    var _partUserInfo = wx.getStorageSync('partUserInfo')
    if (_partUserInfo) {
      that.setData({
        partUserInfo: _partUserInfo
      })
    }
    console.log('on show partUserInfo ', _partUserInfo)
    // 1.加载需求
    if (!that.data.reqDetail) {
      console.log('load req on show ...')
      that.loadDatas(_reqId)
    }
    // 2.加载任务
    if (_taskId) {
      // 2.1有taskId 已经登录了 （可能是自己 也可能是接收者）加载任务 加载会话
      that.loadTask(_taskId)
      that.timer = setInterval(() => {
        that.loadChatList(_taskId)
      }, 1000);

    } else {
      // 2.2没有taskId，判断登录, 加载到taskId
      if (_partUserInfo) { // 加载到taskID
        // 2.2.1 登录了，可能首页过来的
        // 2.2.1.1 判断是不是自己的需求 如果是 跳转 在加载需求是判断了
        // 2.2.1.2 如果不是 查一下有没有task 没有的话 啥也不干 显示洽谈
        // 2.2.1.3 有的化 显示列表
        that.loadTaskByCurrUser()
      } else {
        // 2.2.2 未登录，可能首页过来的，啥也不干 显示洽谈
        that.setData({
          isTaskNewFlag: true
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log('exec hide')
    this.clearTimer()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log('exec upload')
    this.clearTimer()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})